-- UIEquips
-- Create by luohj Jan/14/2015
-- 玩家装备界面

require "game/ui/form/equips/UIEquipsOperation"
require "game/ui/form/equips/UIWeaponsExplain"
require "game/ui/form/hero/HeroUtil"
require "game/ui/form/hero/UIPropertyInfo"

UIEquips = class("UIEquips",function()
    return cc.Layer:create();
end);

function UIEquips.create(openType, extraPara)
    return UIEquips.new(openType, extraPara);
end

-- 装备界面打开的方式
EQUIP_OPEN_TYPE_DEFAULT             = 0;    -- 默认打开
EQUIP_OPEN_TYPE_BLACKSMITH          = 1;    -- 工坊打开
EQUIP_OPEN_TYPE_DEMON               = 2;    -- 魔神雕像打开
EQUIP_OPEN_TYPE_HOLY_ITEMS          = 3;    -- 通过圣器界面打开
EQUIP_OPEN_TYPE_WITCH               = 4;    -- 通过巫妖雕像打开
EQUIP_OPEN_TYPE_CREATE_GATE         = 5;    -- 通过创世之们打开
EQUIP_OPEN_TYPE_DARK_DRAGON         = 6;    -- 通过黑暗龙雕像打开
EQUIP_OPEN_TYPE_MONSTER_CAPTAIN     = 7;    -- 通过海怪船长打开
EQUIP_OPEN_TYPE_SUBMIT_ALL          = 8;    -- 通过提交方式打开（除了神器等特殊物品外均可提交）
EQUIP_OPEN_TYPE_TREE_HOUSE          = 9;    -- 通过树屋方式打开
EQUIP_OPEN_TYPE_ANVIL               = 10;   -- 通过附魔师铁砧打开
EQUIP_OPEN_TYPE_APPOINT_ITEMS       = 11;   -- 指定物品打开（可复用）
EQUIP_OPEN_TYPE_HELMET              = 12;   -- 头盔（受伤的反叛军）

-- 装备格最大行数和列数
local MAX_GRID_ROW    = 3;
local MAX_GRID_COLUMN = 5;
local totalHeight = MAX_GRID_ROW * (94 + 5) - 5 + (7 * 2);

-- 每一页包裹的格子数量
local PAGE_GRID_COUNT = MAX_GRID_ROW*MAX_GRID_COLUMN;

-- 一页包裹的宽高
local PAGE_WIDTH  = 510;
local PAGE_HEIGHT = 300;

-- 模型缩放比例
local HERO_MODEL_SCALE = 0.667;

-- 装备页
local me = nil;

-- 当前在第几个分页，当页面重新打开是需要保持
local currentPageIndex = 0;

-- 内部函数声明
local switchPage;
local redrawEmptyGrid;

-- 关闭装备页面
function closeEquipUI()
    UIMgr.getCurrentScene():removeFormByName("UIEquips");
end

-- 构造函数
-- @param openType     界面打开的方式
-- @param extraPara    附加参数
function UIEquips:ctor(openType, extraPara)
    -- 初始化
    me = self;
    self:setName("UIEquips");
    local node = cc.CSLoader:createNode("layout/equip/equip.csb");
    self:addChild(node);
    self.node = node;
    local CT = node:getChildByName("CT");
    local panel = CT:getChildByName("page_view");

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    openType = openType or EQUIP_OPEN_TYPE_DEFAULT;
    self.openType = openType;
    self.extraPara = extraPara or {};

    if openType == EQUIP_OPEN_TYPE_BLACKSMITH then
        -- 通过工坊方式开始，传入可升级的装备偏向
        self.upgradeStyle = self.extraPara["upgradeStyle"] or
            { EQUIP_STYLE_PHYSIC, EQUIP_STYLE_MAGIC, };
    end

    -- 创世之门打开时特定的钥匙
    if openType == EQUIP_OPEN_TYPE_CREATE_GATE then
        self.keysIds = FormulaM.invoke("GET_CREATIONGATE_KEYS");
    end

    if openType == EQUIP_OPEN_TYPE_ANVIL then
        -- 通过道具铁砧方式开始，传入可升级的装备偏向
        self.upgradeStyle = self.extraPara["upgradeStyle"] or
            { EQUIP_STYLE_PHYSIC, EQUIP_STYLE_MAGIC, };
    end

    self.CT = CT;
    local BT = node:getChildByName("BT");
    self.BT = BT;

    self.panel = panel;
    self.data = {};

    -- 设置下滚动面板的信息
    panel:removeAllPages();
    panel:setCustomScrollThreshold(100);
    panel:setUsingCustomScrollThreshold(true);

    -- 注册翻页事件
    local function pageViewEvent(sender, eventType)
        if eventType == ccui.PageViewEventType.turning then
            currentPageIndex = panel:getCurPageIndex();

            self:switchNext();
            self:redraw();
        end
    end
    panel:addEventListener(pageViewEvent);

    self.equipTypes = { EQUIP_TYPE_TRUMP, EQUIP_TYPE_RING, EQUIP_TYPE_NECKLACE, EQUIP_TYPE_HELMET,
                       EQUIP_TYPE_CLOAK, EQUIP_TYPE_ARMOR,EQUIP_TYPE_GLOVE, EQUIP_TYPE_WEAPON,
                       EQUIP_TYPE_MEDAL, EQUIP_TYPE_BOOT, EQUIP_TYPE_BELT, EQUIP_TYPE_RISKER};

    -- 注册点击事件
    self:registerTouchEvent(node);

    -- 适配
    self:resize();

    -- 设置panel尺寸
    panel:setContentSize(panel:getContentSize().width, totalHeight);

    -- 绘制下
    self:show();

    -- 保持下分页
    if currentPageIndex < self.pageCount then
        panel:scrollToPage(currentPageIndex);
    end
end

-- 创建一个页面的内容
function UIEquips:createOnePage(layout, pageIndex)
    local iconNode = cc.CSLoader:createNode("layout/equip/equip_item.csb");
    local widget = replaceNodeWithWidget(iconNode);
    local iconWidth = 94;
    local iconHeight = 94;
    local topHGap  = 7;
    local leftWGap = 21;
    local hGap, wGap = 5, 10;

    local index = pageIndex*PAGE_GRID_COUNT + 1;
    for row = 1, MAX_GRID_ROW do
        for col = 1, MAX_GRID_COLUMN do
            local child = widget:clone();
            child:setName("magic" .. index);

            -- 先隐藏
            child:setVisible(false);

            local x = (col - 1) * (iconWidth + wGap) + iconWidth / 2 + leftWGap;
            local y = totalHeight - (row * iconHeight + (row - 1) * hGap)  + iconHeight / 2 - topHGap;

            self:registerItemTouchEvent(child);
            index = index + 1;
            child:setPositionX(x);
            child:setPositionY(y);
            layout:addChild(child);
        end
    end

    -- 标记下已经创建过了
    layout.created = true;
end

-- 在地牢中，本页面不析构，在初始化后需要show一把
function UIEquips:show(equipType)
    -- 注册事件处理回调函数
    self:registerEventCallback();

    self:setVisible(true);
    if UIDungeonMgr:getCurLevel() then
        UIDungeonMgr:getCurLevel():hideMenu();
    end

    -- 初始化view
    self:init(equipType);

    -- 重绘
    self:redraw();

    self:redrawPageBtn();
end

-- 初始化
function UIEquips:init(equipType)
    -- 处于变身状态，创建变身状态的模型，否则创建普通模型
    local shapeId = ShapeChangeM.getShapeChangeId();
    if type(shapeId) == "number" and shapeId ~= -1 then
        -- 获取当前的出战宠物
        local pet = ME.user:getActivePet();
        local userPetId = pet.classId;

        self:createShapeChangeModel(shapeId);
    else
        -- 创建英雄模型
        self:createHeroModel();
    end

    self:initView(equipType);
end

-- 还原初始位置
function UIEquips:resetPos()
    -- 重新适配
    self:resize();
end

-- 重绘当前页
function UIEquips:redrawCurPage()
    local pageIndex = self.panel:getCurPageIndex();
    switchPage(self, self.panel, pageIndex);
end

-- 清理一下空格
function UIEquips:cleanEmptyGrid()
    local pageCount = #self.panel:getPages();
    local pageIndex = self.panel:getCurPageIndex();
    local itemCount = #self.data;
    for i = pageIndex, pageCount - 1 do
        local page = self.panel:getPage(i);

        -- 计算本页起始索引
        local index = i*PAGE_GRID_COUNT + 1;
        for j = 1, PAGE_GRID_COUNT do
            local child = page:getChildByName("magic" .. index);

            -- 将超过物品数量的格子都刷成空格
            if index > itemCount and child ~= nil then
                redrawEmptyGrid(child);
            end

            index = index + 1;
        end
    end
end

-- 注册事件处理回调函数
function UIEquips:registerEventCallback()
    EventMgr.removeAll("UIEquips");

    -- 关注穿戴装备的事件
    EventMgr.register("UIEquips", event.EQUIP, function(classId)
        -- 一些界面开启时，不用显示装备界面，过滤下
        local filter = { "UIEngineeringManual", };
        for _, f in ipairs(filter) do
            local uiCurForm = UIMgr:getCurrentScene():getCurrentForm();
            if uiCurForm:getName() == f then
                return;
            end
        end

        local function callback()
            self:show(EquipM.query(classId, "type"));
        end
        performWithDelay(self, callback, 0.01);
    end);

    -- 关注卸下装备的事件
    EventMgr.register("UIEquips", event.UNEQUIP, function(params)
        local function callback()
            self:show();
        end
        performWithDelay(self, callback, 0.01);
    end);

    -- 关注拆分装备的事件
    EventMgr.register("UIEquips", event.SPLIT_EQUIP, function(params)
        local function callback()
            self:show();

            -- 弹出奖励框
            local showResolveConfirmAgain = function()
                if UIMgr:getCurrentScene():isOpen("UIEquipsOperation") and type(params["classId"]) == "number" then
                    UIEquipsOperation:showResolveConfirm(params["classId"]);
                end
            end

            showBonusNotifyForm(getLocStr("equip_resolve"), { {2, "search_point", params["gainSp"]} }, showResolveConfirmAgain);
        end
        performWithDelay(self, callback, 0.01);
    end);

    -- 锻造宝物成功事件
    EventMgr.register("UIEquips", event.FORGE_SUCCESS, function(args)
        local function callback()
            self:show();
        end
        performWithDelay(self, callback, 0.01);
    end);

    -- 卷轴合成事件
    EventMgr.register("UIEquips", event.COMPOUND_SPELL, function(args)
        local function callback()
            self:show();
        end
        performWithDelay(self, callback, 0.01);
    end);

    -- 工程学手册赋予装备属性
    EventMgr.register("UIEquips", event.MANUAL_APPLY_EQUIP_PROP, function()
        self:redrawAttrib()
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            me = nil;
            EventMgr.removeAll("UIEquips");
            if nil ~= self.effectNode and self.effectNode:isExisted() then
                self.effectNode:removeFromParent();
                self.effectNode = nil;
            end
            if UIDungeonMgr:getCurLevel() then
                -- 工坊界面、道具选择目标界面打开时，不能将头部菜单显示出来
                if (not UIMgr.getCurrentScene():isOpen("UIDungeonBlacksmith")) and
                   (not UIMgr.getCurrentScene():isOpen("UIPropertySelectTarget")) then
                    UIDungeonMgr:getCurLevel():showMenu();
                end
            end
        end
    end);
end

-- 是否是禁止提交的物品
function UIEquips:isForbidSubmit(classId)
    local equipType = EquipM.query(classId, "type");
    if equipType == EQUIP_TYPE_WEAPON or equipType == EQUIP_TYPE_MEDAL then
        -- 武器或徽章
        return true;
    end

    if ArtifactM.isArtifact(classId) then
        -- 神器
        return true;
    end

    return false;
end

-- 判断是否是武器或徽章
function UIEquips:isEquip(classId)
    local type = EquipM.query(classId, "type");
    if type == EQUIP_TYPE_WEAPON or type == EQUIP_TYPE_MEDAL or type == EQUIP_TYPE_COSTUME then
        return false;
    end
    return true;
end

-- 判断是否特殊宝物
function UIEquips:isSpecialTreasure(classId)
    local type = ItemM.query(classId, "type");
    if type == ITEM_TYPE_SPECIAL_TREASURE then
        return true;
    end
    return false;
end

-- 获取所有道具信息
function UIEquips:getAllProperties()
    local ids = PropertyM.getUserProperties();
    if #ids == 0 then
        return {};
    end

    -- 获得可携带的道具的id
    local carriableItems = ItemM.getAllCarriableItems();
    local  dungeonItem = ME.user.dbase:query("dungeon_item", {});

    local ret = {};
    for _, id in pairs(ids) do
        local info = PropertyM.query(id);

        if table.indexOf(carriableItems, id) ~= -1 then

            if dungeonItem[id] == nil then
                dungeonItem[id] = 0;
            end
            if dungeonItem[id] > 0 then
                table.insert(ret, info);
            end
        elseif PropertyM.isDungeonProperty(id) then
            -- 迷宫内的道具
            table.insert(ret, info);
        end
    end
    return ret;
end

-- 获取英雄的所有装备
function UIEquips:getHeroAllEquips()
    self.data = {};
    local allEquips = EquipM.queryUserAllEquip();
    if allEquips then
        local equips = {};
        for key, var in pairs(allEquips) do
            if self:isEquip(var) then
                table.insert(equips,var)
            end
        end
        self.data = self:getEquipsInfo(equips);
    end
end

-- 获取神器信息
function UIEquips:getArtifactInfo(classId)
    local ret = {};
    if classId == nil then
        return ret;
    end;

    local data = {};
    local Info   = ItemM.query(classId);
    if Info then
        data.class_id = Info["class_id"] or "";
        data.icon = Info["icon"] or -1;

        if Info["class_id"] then
            data.count = ItemM.getAmount(ME.user,data.class_id);
            data.type = ItemM.query(data.class_id,"type");
            data.rank = FormulaM.invoke("CALC_ARTIFACT_RANK", data.class_id);
        end

    end
    return data;
end

-- 获取装备信息
function UIEquips:getEquipsInfo(classIdS)
    local ret = {};
    if classIdS == nil then
        return ret;
    end;

    for _, var in pairs(classIdS) do
        local Info   = ItemM.query(var);
        if Info then
            local data = {};
            data.class_id = Info["class_id"] or "";
            data.icon = Info["icon"] or -1;

            if Info["class_id"] then
                data.count = ItemM.getAmount(ME.user,data.class_id);
                data.type = EquipM.query(data.class_id, "type");
                data.rank = EquipM.getRealRank(data.class_id);
                data.style = EquipM.query(data.class_id, "style");
            end
            table.insert(ret, data);
        end
    end
    return ret;
end

function UIEquips:redrawAttrib()
    -- 设置标题
    local captionLabel = findChildByName(self.CT, "bg4/Text_1");
    TextStyleM.setTextStyle(captionLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, nil, nil, nil, nil, nil, true);
    captionLabel:setString(getLocStr("package"));

    -- 设置攻击力 getAttack attack_attribute
    local attackLabel = findChildByName(self.BT, "attack_attribute/attack_label");
    TextStyleM.setTextStyle(attackLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true, -4);
    attackLabel:setString(ME.user:getAttack());

    -- 设置当前生命值
    local lifeCurrentLabel = findChildByName(self.BT, "life_attribute/surplus_lift_label");
    local currentHpValue = ME.user:getHp();
    TextStyleM.setTextStyle(lifeCurrentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true, -4);
    lifeCurrentLabel:setString(currentHpValue);

    -- 设置最大生命值
    local lifeMaxLabel = findChildByName(self.BT, "life_attribute/all_life_label");
    local maxHpValue = ME.user:getMaxHp();
    TextStyleM.setTextStyle(lifeMaxLabel, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_WHITE, true, -4);
    lifeMaxLabel:setString("/" .. maxHpValue);

    -- 设置魔力值
    local magicPowerLabel = findChildByName(self.BT, "magic_power_attribute/magic_attribute_label");
    local magicValue = ME.user:getMagic();
    TextStyleM.setTextStyle(magicPowerLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true, -4);
    magicPowerLabel:setString(magicValue);

    -- 设置当前魔法值
    local mpCurrentLabel = findChildByName(self.BT, "magic_attribute/surplus_magic_attribute_label");
    local currentMpValue = ME.user:getMp();
    TextStyleM.setTextStyle(mpCurrentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true, -4);
    mpCurrentLabel:setString(currentMpValue);

    -- 设置最大魔法值
    local mpMaxLabel = findChildByName(self.BT, "magic_attribute/all_magic_attribute_label");
    local maxMpValue = ME.user:getMaxMp();
    TextStyleM.setTextStyle(mpMaxLabel, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_WHITE, true, -4);
    mpMaxLabel:setString("/" .. maxMpValue);
end

-- 收集物品信息
function UIEquips:collectItemInfo()
    -- 获取英雄的所有装备
    self:getHeroAllEquips();

    -- 添加神器装备
    local artifactId = ME.user:getCarryArtifact();
    if artifactId ~= 0 then
        local amount = ItemM.getAmount(ME.user, artifactId);
        if amount > 0 then
            local artifactInfo= self:getArtifactInfo(artifactId);
            table.insert(self.data, artifactInfo);
        end
    end

    -- 装备排序
    local function sortItems(a, b)
        -- 关卡特殊套装，在最前并按ID排序
        if a.style == EQUIP_STYLE_EXCLUSIVE and b.style ~= EQUIP_STYLE_EXCLUSIVE then
            return true;
        elseif a.style ~= EQUIP_STYLE_EXCLUSIVE and b.style == EQUIP_STYLE_EXCLUSIVE then
            return false;
        elseif a.style == EQUIP_STYLE_EXCLUSIVE and b.style == EQUIP_STYLE_EXCLUSIVE then
            return a.class_id < b.class_id;
        end

        -- 特殊物品排前面
        if self:isSpecialTreasure(a.class_id) and not self:isSpecialTreasure(b.class_id) then
            return true;
        elseif not self:isSpecialTreasure(a.class_id) and self:isSpecialTreasure(b.class_id) then
            return false;
        end

        if a.rank < b.rank then
            return true;
        elseif a.rank > b.rank then
            return false
        end

        if a.type < b.type then
            return true;
        elseif a.type > b.type then
            return false;
        end

        return a.class_id < b.class_id;
    end

    -- 排序规则按部位降序排列，同部位按阶位降序排列（部位顺序以头文件定义的宏为准）
    table.sort(self.data, sortItems);

    -- 获取所有的道具
    local properties = self:getAllProperties();

    local function sortProperties(a, b)


        local targetA = PropertyM.query(a.class_id, "target");
        local targetB = PropertyM.query(b.class_id, "target");

        -- 工程学手册排在最前面
        if targetA == PROPERTY_MANUAL and targetB ~= PROPERTY_MANUAL then
            return true;
        elseif targetA ~= PROPERTY_MANUAL and targetB == PROPERTY_MANUAL then
            return false;
        elseif targetA == PROPERTY_SUBMIT and targetB ~= PROPERTY_SUBMIT then
            return false;
        elseif targetA ~= PROPERTY_SUBMIT and targetB == PROPERTY_SUBMIT then
            return true;
        end

        return a.class_id < b.class_id;
    end

    -- 根据道具id升序
    table.sort(properties, sortProperties);

    -- 道具排在装备前面
    self.data = table.append(properties, self.data);
end

-- 初始化窗口
function UIEquips:initView(equipType)
    -- 初始化英雄属性
    self:redrawAttrib();

    -- 收集道具信息
    self:collectItemInfo();

    -- 将英雄已经装备上的装备显示在界面上
    self:showUsedEquips(equipType);

    local itemCount = math.max(PAGE_GRID_COUNT, #self.data);
    local pageCount = math.ceil(itemCount / (PAGE_GRID_COUNT));
    self.totalCount = pageCount * PAGE_GRID_COUNT;
    self.pageCount = pageCount;

    -- 如果分页不存在需要创建下
    local panel = self.panel;
    for i = 1, pageCount do
        local layout = panel:getPage(i - 1);
        if not layout then
            local layout = ccui.Layout:create();
            layout:setContentSize(panel:getContentSize());
            panel:addPage(layout);
        end
    end
    -- 超过分页的页面需要删除掉
    local pages = panel:getPages();
    for i = pageCount + 1, #pages do
        panel:removePageAtIndex(i - 1);
    end

    -- 切换到下一页
    self:switchNext();
end

-- 将英雄已经装备上的装备显示在界面上
function UIEquips:showUsedEquips(equipType)

    -- 获取英雄对象
    local pet = ME.user:getActivePet();
    assert(pet, "当前出战宠物不存在!");

    for i = 1, 12 do
        local classId = EquipM.getEquip(self.equipTypes[i], 1);
        if i == 8 or i == 9 then
            classId = EquipM.getHeroEquip(pet, self.equipTypes[i], 1);
        end
        local node = findChildByName(self.CT, "AA" .. i);
        local btn = findChildByName(node, "btn");
        btn.type = self.equipTypes[i];
        local newItem = findChildByName(node, "new_item");
        local mask = findChildByName(node, "mask");
        local rankNode = findChildByName(node, "rank");
        local defaultIcon = findChildByName(node, "default_icon");
        local titleLabel = findChildByName(node, "title");

        if classId then
            local iconIndex = ItemM.query(classId, "icon");
            btn.classId = classId;
            btn:loadTexture(getItemIconPath(iconIndex));
            btn:setVisible(true);
            btn:setTouchEnabled(true);

            -- 增加新道具显示
            if not ItemM.isNewItem(classId) then
                -- 不在新道具列表中，不显示
                newItem:setVisible(false);
            else
                newItem:setVisible(true);

                -- 提示图标需要略微的放大缩小
                playNewItemEffect(newItem);

                -- 从新道具列表中去除
                ItemM.cleanNewItemList(classId);
            end

            if self.openType == EQUIP_OPEN_TYPE_BLACKSMITH then
                -- 通过工坊打开界面时
                if not DungeonBlacksmithM.canEquipUpgraded(classId, self.upgradeStyle, true) then
                    -- 无法升级，显示蒙版
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_DEMON then
                -- 通过魔神雕像打开
                local submited = self.extraPara["submited"] or {};

                if not EquipM.isEquipment(classId) or ArtifactM.isArtifact(classId) then
                    -- 非装备，显示蒙版
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_HOLY_ITEMS then
                -- 通过圣器界面打开
                -- 如果不是圣器，需要显示蒙版
                if not HolyItemsM.isHolyItems(classId, self.extraPara["holy_type"]) then
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_WITCH then
                -- 巫妖雕像
                -- 所有物品都可以显示
                -- TODO: 除了神器
                if ArtifactM.isArtifact(classId) then
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_TREE_HOUSE then
                -- 树屋
                local showItemList = TreeHouseM.getDefaultList();
                if TreeHouseM.hasSpecialItem() then
                    -- 有特殊物品，随便提交
                    if not TreeHouseM.canSubmitItem(classId)
                        or table.indexOf(self.extraPara["submited"], classId) ~= -1 then
                        -- 不是可以提交的或者已经提交过了
                        mask:setVisible(true);
                    else
                        mask:setVisible(false);
                    end
                else
                    -- 没有特殊物品，按顺序提交
                    if classId ~= showItemList[self.extraPara["index"]] then
                        mask:setVisible(true);
                    else
                        mask:setVisible(false);
                    end
                end
            elseif self.openType == EQUIP_OPEN_TYPE_CREATE_GATE then
                if -1 ~= table.indexOf(self.extraPara["keyIds"], classId) then
                    mask:setVisible(false);
                else
                    mask:setVisible(true);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_DARK_DRAGON
                or self.openType == EQUIP_OPEN_TYPE_MONSTER_CAPTAIN
                or self.openType == EQUIP_OPEN_TYPE_APPOINT_ITEMS then
                -- 非提交物品不显示(这个分支可作为比较通用的分支)
                local submited = self.extraPara["submited"] or {};
                if table.indexOf(submited, classId) == -1  then
                    -- 显示蒙版
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_SUBMIT_ALL then
                -- 提交
                if self:isForbidSubmit(classId) then
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_ANVIL then
                -- 通过铁砧打开
                if not RiskerEquipM.canEquipUpgraded(classId, true, self.upgradeStyle) then
                    -- 无法升级，显示蒙版
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_HELMET then
                -- 头盔
                if not self:isForbidSubmit(classId)
                    and EquipM.isEquipment(classId)
                    and EquipM.query(classId, "type") == EQUIP_TYPE_HELMET then
                    mask:setVisible(false);
                else
                    mask:setVisible(true);
                end
            else
                mask:setVisible(false);
            end

            -- 增加装备的阶位显示
            -- 先移除所有子控件
            rankNode:removeAllChildren();
            local rank = ItemM.query(classId, "rank");

            if ArtifactM.isArtifact(classId) then
                rank = FormulaM.invoke("CALC_ARTIFACT_RANK", classId);
            end

            if EquipM.isEquipment(classId) then
                rank = EquipM.getRealRank(classId);
            end
            if rank ~= nil and EquipM.isEquipment(classId) then
                local rankLayer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.6);
                rankLayer:setScale(0.75);
                rankNode:addChild(rankLayer);
                rankNode:setVisible(true);
            end

            defaultIcon:setVisible(false);
            titleLabel:setVisible(false);

            -- 穿戴装备，需要播放穿戴成功的效果
            if equipType ~= nil and equipType == self.equipTypes[i] then
                local _, effectNode = playEffect(btn, 1186, 45, 45);
                self.effectNode = effectNode;
            end
        else
            btn:setVisible(false);
            defaultIcon:loadTexture("images/ui/equip/equip" .. i .. ".png");
            defaultIcon:setVisible(true);
            mask:setVisible(false);
            newItem:setVisible(false);
            rankNode:setVisible(false);
        end
    end
end

-- 创建英雄模型
function UIEquips:createHeroModel()
    local headImg = self.CT:getChildByName("hero_head");
    local modelNode = self.CT:getChildByName("model_node");

    -- 获取当前出战英雄
    local hero = ME.user:getActivePet();
    local iconPath = getHeroLargeIconPath(hero:getLargeIcon());

    createHeroModel(hero:getModelId(), headImg, modelNode, HERO_MODEL_SCALE, iconPath);
end

-- 创建变身后的英雄模型
function UIEquips:createShapeChangeModel(shapeId)
    local headImg = self.CT:getChildByName("hero_head");
    local modelNode = self.CT:getChildByName("model_node");

    -- 查询变身信息
    local shapeInfo = ShapeChangeM.query(shapeId);

    -- 获取当前出战英雄
    local iconPath = getHeroLargeIconPath(shapeInfo["icon"]);
    local animation = shapeInfo["animation"];
    modelNode:removeAllChildren();
    createShapeChangeMode(shapeId, headImg, animation, modelNode, HERO_MODEL_SCALE, iconPath);
end

-- 绘制空格
function redrawEmptyGrid(child)
    local iconImg = child:getChildByName("btn");
    iconImg:setVisible(false);

    local countLabel = child:getChildByName("count");
    countLabel:setVisible(false);

    local numLabel = child:getChildByName("num");
    numLabel:setVisible(false);

    local rankNode = child:getChildByName("rank");
    rankNode:setVisible(false);

    local newItem = child:getChildByName("new_item");
    newItem:setVisible(false);
end

-- 重绘
function UIEquips:redraw(refreshNewItem)
    local curPageIndex = self.panel:getCurPageIndex();
    local itemCount = #self.data;
    local startIndex = curPageIndex * PAGE_GRID_COUNT + 1 ;
    local endIndex = (curPageIndex + 1) * PAGE_GRID_COUNT;
    local page = self.panel:getPage(curPageIndex);
    if page == nil then
        return;
    end
    if endIndex > itemCount then endIndex = itemCount end

    -- 获得可携带的道具的id
    local carriableItems = ItemM.getAllCarriableItems();
    local dungeonItem = ME.user.dbase:query("dungeon_item", {});

    -- 逐个格子绘制
    if page.created == nil then
        self:createOnePage(page, curPageIndex);
    end
    for i = 1, PAGE_GRID_COUNT do
        local child = page:getChildByName("magic" .. startIndex);
        if child == nil then
            return;
        end
        child:setVisible(true);

        if startIndex <= endIndex and self.data[startIndex] then
            local classId = self.data[startIndex]["class_id"];
            local countLabel = child:getChildByName("num");
            local iconImg = child:getChildByName("btn");
            iconImg:setVisible(true);
            local rankNode = child:getChildByName("rank");
            local newItem = child:getChildByName("new_item");
            local amount = 0;

            if PropertyM.isProperty(classId) then
                -- 道具
                -- 设置道具数量
                amount = ItemM.getAmount(ME.user, classId);
                if table.indexOf(carriableItems, classId) ~= -1 then
                    amount = dungeonItem[classId];
                end
                countLabel:setString(tonumber(amount));

                -- 设置图标
                local icon = ItemM.query(classId, "icon");
                iconImg:loadTexture(getItemIconPath(icon));
            elseif self.data[startIndex]["count"] then
                -- 宝物
                -- 设置物品个数
                amount = self.data[startIndex]["count"];
                countLabel:setString(tonumber(amount));

                -- 设置图标
                local iconIndex = self.data[startIndex]["icon"];
                iconImg:loadTexture(getItemIconPath(iconIndex));
            end;

            countLabel:setVisible(amount > 1);

            -- 增加装备的阶位显示
            -- 先移除所有子控件
            rankNode:removeAllChildren();
            local rank = ItemM.query(classId, "rank");

            if ArtifactM.isArtifact(classId) then
                rank = FormulaM.invoke("CALC_ARTIFACT_RANK", classId);
            end

            if EquipM.isEquipment(classId) then
                rank = EquipM.getRealRank(classId);
            end
            if rank ~= nil and EquipM.isEquipment(classId) then
                local rankLayer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.6);
                rankLayer:setScale(0.75);
                rankNode:setVisible(true);
                rankNode:addChild(rankLayer);
            end

            TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);

            -- 增加新道具显示
            if ItemM.isNewItem(classId) then
                newItem:setVisible(true);

                -- 提示图标需要略微的放大缩小
                playNewItemEffect(newItem);
            else
                if refreshNewItem == nil or refreshNewItem == classId then
                    -- 不在新道具列表中，不显示
                    newItem:setVisible(false);
                end
            end

            -- 如果是当前页，则从新道具列表中移除
            if self.panel:getCurPageIndex() == 0 then
                ItemM.cleanNewItemList(classId);
            end

            local mask = child:getChildByName("mask")
            if self.openType == EQUIP_OPEN_TYPE_BLACKSMITH then
                -- 通过工坊打开界面时，不能升级的装备要显示蒙版
                if not DungeonBlacksmithM.canEquipUpgraded(classId, self.upgradeStyle) then
                    -- 显示蒙版
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_ANVIL then
                -- 通过冒险系装备界面时，不能升级的装备要显示蒙版
                if not RiskerEquipM.canEquipUpgraded(classId, false, self.upgradeStyle) then
                    -- 显示蒙版
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_DEMON then
                local submited = self.extraPara["submited"] or {};
                local count = 0;
                for _, id in pairs(submited) do
                    if classId == id then
                        count = count + 1;
                    end
                end

                if not EquipM.isEquipment(classId) or ArtifactM.isArtifact(classId) or ItemM.getAmount(ME.user, classId) <= count then
                    -- 非装备
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_HOLY_ITEMS then
                -- 通过圣器界面打开
                -- 如果不是圣器，需要显示蒙版
                if not HolyItemsM.isHolyItems(classId, self.extraPara["holy_type"]) then
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_WITCH then
                -- 巫妖雕像打开
                -- 所有物品都可以显示
                -- TODO: 除了神器
                if ArtifactM.isArtifact(classId) then
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_TREE_HOUSE then
                -- 树屋
                local showItemList = TreeHouseM.getDefaultList();
                if TreeHouseM.hasSpecialItem() then
                    -- 有特殊物品，随便提交
                    if not TreeHouseM.canSubmitItem(classId)
                        or table.indexOf(self.extraPara["submited"], classId) ~= -1 then
                        -- 不是可以提交的或者已经提交过了
                        mask:setVisible(true);
                    else
                        mask:setVisible(false);
                    end
                else
                    -- 没有特殊物品，按顺序提交
                    if classId ~= showItemList[self.extraPara["index"]] then
                        mask:setVisible(true);
                    else
                        mask:setVisible(false);
                    end
                end
            elseif self.openType == EQUIP_OPEN_TYPE_CREATE_GATE then
                if -1 ~= table.indexOf(self.extraPara["keyIds"], classId) then
                    mask:setVisible(false);
                else
                    mask:setVisible(true);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_DARK_DRAGON
                or self.openType == EQUIP_OPEN_TYPE_MONSTER_CAPTAIN
                or self.openType == EQUIP_OPEN_TYPE_APPOINT_ITEMS then
                local hasSubmited = self.extraPara["has_submited"] or {};
                local count = 0;
                for _, id in pairs(hasSubmited) do
                    if classId == id then
                        count = count + 1;
                    end
                end

                -- 非提交物品不显示(这个分支可作为比较通用的分支)
                local submited = self.extraPara["submited"] or {};
                if table.indexOf(submited, classId) == -1 or ItemM.getAmount(ME.user, classId) <= count then
                    -- 显示蒙版
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_SUBMIT_ALL then
                -- 提交
                if self:isForbidSubmit(classId) then
                    mask:setVisible(true);
                else
                    mask:setVisible(false);
                end
            elseif self.openType == EQUIP_OPEN_TYPE_HELMET then
                -- 头盔
                if not self:isForbidSubmit(classId)
                    and EquipM.isEquipment(classId)
                    and EquipM.query(classId, "type") == EQUIP_TYPE_HELMET then
                    mask:setVisible(false);
                else
                    mask:setVisible(true);
                end
            else
                mask:setVisible(false);
            end

            child.classId = classId;
        else
            -- 绘制空格
            redrawEmptyGrid(child);
        end

        startIndex = startIndex + 1;
    end
end

-- 播放新道具提示效果
function playNewItemEffect(icon)
    local function playNewTipEffect()
        local function scaleChange()
            local scaleUp = cc.ScaleTo:create(0.5, 1);
            local scaleDown = cc.ScaleTo:create(0.5, 0.95);
            local function scaleChangeDone()
                if icon then
                    performWithDelay(icon, scaleChange, 0.2);
                end
            end

            local callFunc = cc.CallFunc:create(scaleChangeDone);
            icon:runAction(cc.Sequence:create(scaleUp, scaleDown, callFunc));
        end

        if icon then
            performWithDelay(icon, scaleChange, 0.2);
        end
    end

    if icon then
        performWithDelay(icon, playNewTipEffect, 0.2);
    end
end

-- 显示武器/徽章信息界面
-- @param classId      装备id
function UIEquips:showUIWeaponsExplain(classId)
    if classId == nil then
        return;
    end

    -- 打开武器/徽章信息界面
    if UIMgr.getCurrentScene():isOpen("UIItemDesc") then
        UIMgr.getCurrentScene():removeFormByName("UIItemDesc");
    end
    local uiWeaponsExplain = UIItemDesc.create(classId);
    UIMgr.getCurrentScene():addForm(uiWeaponsExplain);
end

-- 显示装备操作界面
-- @param classId      装备id
-- @param operateType  操作类型
-- @param isEquiped    是否是穿在身上的装备
function UIEquips:showUIEquipsOperation(classId, operateType, isEquiped)
    -- 打开装备操作界面
    local pet = ME.user:getActivePet();

    if not classId then
        return;
    end

    if self.openType == EQUIP_OPEN_TYPE_DEFAULT then
        -- 默认操作

    elseif self.openType == EQUIP_OPEN_TYPE_BLACKSMITH then
        -- 工坊操作
        operateType = EQUIP_OPERATE_BLACKSMITH;

        -- 如果该装备无法升级，提示玩家
        if not DungeonBlacksmithM.canEquipUpgraded(classId, self.upgradeStyle, isEquiped) then
            alert(getLocStr("this_equip_cannot_upgrade"));
            return;
        end
    elseif self.openType == EQUIP_OPEN_TYPE_HOLY_ITEMS then
        -- 圣器操作
        operateType = EQUIP_OPERATE_BLACKSMITH;
    elseif self.openType == EQUIP_OPEN_TYPE_ANVIL then
        -- 工坊操作
        operateType = EQUIP_OPERATE_BLACKSMITH;

        -- 如果该装备无法升级，提示玩家
        if not RiskerEquipM.canEquipUpgraded(classId, isEquiped, self.upgradeStyle) then
            alert(getLocStr("this_equip_cannot_upgrade"));
            return;
        end
    else
        -- 提交操作
        operateType = EQUIP_OPERATE_SUBMIT;
    end

    -- 打开装备操作界面
    if UIMgr.getCurrentScene():isOpen("UIEquipsOperation") then
        UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
    end

    local uiForm = UIEquipsOperation.create(classId, operateType, isEquiped, self.extraPara);
    UIMgr.getCurrentScene():addForm(uiForm);

    -- 道具查看过了，需要从新道具列表中移除
    ItemM.cleanNewItemList(classId);
    self:redraw(classId);
end

-- 适配
function UIEquips:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册装备点击事件
function UIEquips:registerItemTouchEvent(node)
    local image = node:getChildByName("btn");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then

            -- 如果是道具，打开道具查看界面
            local target = PropertyM.query(node.classId, "target");
            if target == PROPERTY_DIARY then
                -- 是日记，打开日记界面
                local uiForm = UIDiary.create(node.classId);
                UIMgr.getCurrentScene():addForm(uiForm);
                AudioM.playFx("ui_open2");
            elseif target == PROPERTY_BOOK then
                -- 是书籍，打开书籍界面
                local uiForm = UIBookInfo.create(node.classId);
                UIMgr.getCurrentScene():addForm(uiForm);
                AudioM.playFx("ui_open2");
            elseif target == PROPERTY_MANUAL then
                -- 手册
                if EngineeringManualM.canOpen() then
                    local uiForm = UIEngineeringManual.create();
                    UIMgr.getCurrentScene():addForm(uiForm);
                    AudioM.playFx("ui_open2");
                else
                    alert(getLocStr("engineering_manual_cannot_open"));
                end
            elseif PropertyM.isProperty(node.classId) then
                local operateType;
                if self.openType == EQUIP_OPEN_TYPE_DEFAULT then
                    -- 默认方式打开
                    operateType = PROPERTY_OPERATE_DEFAULT;
                else
                    -- 提交方式打开
                    operateType = PROPERTY_OPERATE_SUBMIT;
                end
                UIMgr.getCurrentScene():removeFormByName("UIPropertyInfo");
                local uiPropertyInfo = UIPropertyInfo.create(node.classId, operateType, self.extraPara);
                UIMgr.getCurrentScene():addForm(uiPropertyInfo);
                AudioM.playFx("button_spell");
            else
                -- 打开装备操作界面（第三个参数表示未装备）
                self:showUIEquipsOperation(node.classId, EQUIP_OPERATE_EQUIP, false);
                AudioM.playFx("equip_put");
            end

            -- 道具查看过了，需要从新道具列表中移除
            ItemM.cleanNewItemList(node.classId);
            self:redraw(node.classId);
        end
    end
    AddTouchEventListener(image, onClick)
end

-- 关闭界面
function UIEquips:hideMe()
    UIMgr.getCurrentScene():removeFormByName("UIEquips");
end

-- 注册点击事件
function UIEquips:registerTouchEvent(node)
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            self:hideMe();
        end
    end
    -- AddTouchEventListener在引导时自动发布TAEGET_CLICK事件
    AddTouchEventListener(btnBack, onBackClick);

    -- AddBackEventHandler在BACK按键点击时，自动触发按钮点击事件
    AddBackEventHandler(self, btnBack, btnBack.touchEventListener);

    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册法宝按钮点击事件
    local btnTrump = findChildByName(node, "CT/AA1/btn");
    local btnTrumpNew = findChildByName(node, "CT/AA1/new_item");
    local function onBtnTrumpClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            local classId = EquipM.getEquip(EQUIP_TYPE_TRUMP, 1);
            if classId then
                self:showUIEquipsOperation(classId, EQUIP_OPERATE_UNEQUIP, true);
                btnTrumpNew:setVisible(false);
            end
        end
    end
    btnTrump:addTouchEventListener(onBtnTrumpClick);

    -- 注册戒指按钮点击事件
    local btnRing = findChildByName(node, "CT/AA2/btn");
    local btnRingNew = findChildByName(node, "CT/AA2/new_item");
    local function onBtnRingClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            local classId = EquipM.getEquip(EQUIP_TYPE_RING,1);
            if classId then
                self:showUIEquipsOperation(classId, EQUIP_OPERATE_UNEQUIP, true);
                btnRingNew:setVisible(false);
            end
        end
    end
    btnRing:addTouchEventListener(onBtnRingClick);

    -- 注册项链 按钮点击事件
    local btnNeckLace = findChildByName(node, "CT/AA3/btn");
    local btnNeckLaceNew = findChildByName(node, "CT/AA3/new_item");
    local function onBtnNeckLaceClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            local classId = EquipM.getEquip(EQUIP_TYPE_NECKLACE,1);
            if classId then
                self:showUIEquipsOperation(classId, EQUIP_OPERATE_UNEQUIP, true);
                btnNeckLaceNew:setVisible(false);
            end
        end
    end
    btnNeckLace:addTouchEventListener(onBtnNeckLaceClick);

    -- 注册头盔按钮点击事件
    local btnHelmet = findChildByName(node, "CT/AA4/btn");
    local btnHelmetNew = findChildByName(node, "CT/AA4/new_item");
    local function onBtnHelmetClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            local classId = EquipM.getEquip(EQUIP_TYPE_HELMET,1);
            if classId then
                self:showUIEquipsOperation(classId, EQUIP_OPERATE_UNEQUIP, true);
                btnHelmetNew:setVisible(false);
            end
        end
    end
    btnHelmet:addTouchEventListener(onBtnHelmetClick);

    -- 注册斗篷按钮点击事件
    local btnCloak = findChildByName(node, "CT/AA5/btn");
    local btnCloakNew = findChildByName(node, "CT/AA5/new_item");
    local function onBtnCloakClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            local classId = EquipM.getEquip(EQUIP_TYPE_CLOAK,1);
            if classId then
                self:showUIEquipsOperation(classId, EQUIP_OPERATE_UNEQUIP, true);
                btnCloakNew:setVisible(false);
            end
        end
    end
    btnCloak:addTouchEventListener(onBtnCloakClick);

    -- 注册铠甲按钮点击事件
    local btnArmor = findChildByName(node, "CT/AA6/btn");
    local btnArmorNew = findChildByName(node, "CT/AA6/new_item");
    local function onBtnArmorClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            local classId = EquipM.getEquip(EQUIP_TYPE_ARMOR, 1);
            if classId then
                self:showUIEquipsOperation(classId, EQUIP_OPERATE_UNEQUIP, true);
                btnArmorNew:setVisible(false);
            end
        end
    end
    btnArmor:addTouchEventListener(onBtnArmorClick);

    -- 注册手套按钮点击事件
    local btnGlove = findChildByName(node, "CT/AA7/btn");
    local btnGloveNew = findChildByName(node, "CT/AA7/new_item");
    local function onBtnGloveClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            local classId = EquipM.getEquip(EQUIP_TYPE_GLOVE,1);
            if classId then
                self:showUIEquipsOperation(classId, EQUIP_OPERATE_UNEQUIP, true);
                btnGloveNew:setVisible(false);
            end
        end
    end
    AddTouchEventListener(btnGlove, onBtnGloveClick);

    -- 注册武器按钮点击事件
    local btnweapon = findChildByName(node, "CT/AA8/btn");
    local function onBtnweaponClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            if sender.classId then
                self:showUIWeaponsExplain(sender.classId);
            end
        end
    end
    btnweapon:addTouchEventListener(onBtnweaponClick);

    -- 注册徽章按钮点击事件
    local btnBadge = findChildByName(node, "CT/AA9/btn");
    local function onBtnBadgeonClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            if sender.classId then
                self:showUIWeaponsExplain(sender.classId);
            end
        end
    end
    btnBadge:addTouchEventListener(onBtnBadgeonClick);

    -- 注册靴子按钮点击事件
    local btnBoot = findChildByName(node, "CT/AA10/btn");
    local btnBootNew = findChildByName(node, "CT/AA10/new_item");
    local function onBtnBootonClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            local classId = EquipM.getEquip(EQUIP_TYPE_BOOT,1);
            if classId then
                self:showUIEquipsOperation(classId, EQUIP_OPERATE_UNEQUIP, true);
                btnBootNew:setVisible(false);
            end
        end
    end
    btnBoot:addTouchEventListener(onBtnBootonClick);

    -- 注册腰带按钮点击事件
    local btnBelt = findChildByName(node, "CT/AA11/btn");
    local btnBeltNew = findChildByName(node, "CT/AA11/new_item");
    local function onBtnBeltonClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            local classId = EquipM.getEquip(EQUIP_TYPE_BELT, 1);
            if classId then
                self:showUIEquipsOperation(classId, EQUIP_OPERATE_UNEQUIP, true);
                btnBeltNew:setVisible(false);
            end
        end
    end
    btnBelt:addTouchEventListener(onBtnBeltonClick);

    -- 注册冒险系装备点击事件
    local btnRisker = findChildByName(node, "CT/AA12/btn");
    local btnRiskerNew = findChildByName(node, "CT/AA12/new_item");
    local function onBtnRiskeronClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            local classId = EquipM.getEquip(EQUIP_TYPE_RISKER, 1);
            if classId then
                self:showUIEquipsOperation(classId, EQUIP_OPERATE_RISKER, true);
                btnRiskerNew:setVisible(false);
            end
        end
    end
    btnRisker:addTouchEventListener(onBtnRiskeronClick);

    -- 注册'上一页'按钮点击事件
    local btnPrevious = findChildByName(self.CT, "btn_left_panel");
    local function onPreviousClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_tiny");
            local curPageIndex = self.panel:getCurPageIndex();
            if curPageIndex <= 0 then
                -- 已经是第一页，不处理
                cclog("当前已经是第一页了。");
                return;
            end
            -- 切换至上一页
            switchPage(self, self.panel, curPageIndex - 1);
            self:switchNext();
            self:redraw();
        end
    end
    btnPrevious:addTouchEventListener(onPreviousClick);

    -- 注册'下一页'按钮点击事件
    local btnNext = findChildByName(self.CT, "btn_right_panel");
    local function onNextClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_tiny");
            local allPage = self.panel:getPages();
            local total = #allPage
            local curPageIndex = self.panel:getCurPageIndex();
            if curPageIndex >= total - 1 then
                cclog("当前已经是最后一页了。");
                return;
            end
            -- 切换至上一页
            switchPage(self, self.panel, curPageIndex + 1);
            self:switchNext();
            self:redraw();
        end
    end
    btnNext:addTouchEventListener(onNextClick);
end

function UIEquips:switchNext()
    local pageCount = self.pageCount;
    local btnPrevious = findChildByName(self.CT, "btn_left");
    local btnNext = findChildByName(self.CT, "btn_right");
    if currentPageIndex >= pageCount then
        currentPageIndex = pageCount - 1;
    end

    btnPrevious:setVisible(currentPageIndex > 0);
    btnNext:setVisible(pageCount - 1 > currentPageIndex);
end

-- 翻页
function switchPage(self, pageView, toPageIndex)
    pageView:scrollToPage(toPageIndex);
end

-- 检查下当前页面装备数量是不是超过当前页
function UIEquips:isPagesOver()
        -- 收集道具信息
    self:collectItemInfo();

    local itemCount = math.max(PAGE_GRID_COUNT, #self.data);
    local pageCount = math.ceil(itemCount / (PAGE_GRID_COUNT));
    local pageIndex = self.panel:getCurPageIndex();

    if pageCount > 1 + pageIndex then
        return true;
    end

    return false;
end

-- 重绘下的按钮
function UIEquips:redrawPageBtn()
    -- 在第一页没有左边的按钮
    local pageIndex = self.panel:getCurPageIndex();

    local btnPrevious = findChildByName(self.CT, "btn_left");
    btnPrevious:setVisible(pageIndex > 0);

    -- 如果当前页小于总页数显示右边的按钮
    local btnNext = findChildByName(self.CT, "btn_right");

    local pageCount = #self.panel:getPages();

    if pageIndex < pageCount - 1 then
        btnNext:setVisible(true);
    else
        btnNext:setVisible(false);
    end
end